<template>
  <div class="container">
    <el-card class="tree-card">
      <template #header>
        <div class="card-header">
          <el-icon>
            <Folder/>
          </el-icon>
          <span>组织树</span>
        </div>
      </template>

      <div class="tree-search">
        <el-input
            v-model="treeFilterText"
            placeholder="组织名称"
            clearable
            @input="filterTree"
        >
          <template #prefix>
            <el-icon>
              <Search/>
            </el-icon>
          </template>
        </el-input>
      </div>

      <div class="tree-container">
        <el-tree
            ref="treeRef"
            class="filter-list"
            :data="filteredTreeData"
            :props="treeProps"
            node-key="id"
            default-expand-all
            @node-click="handleNodeClick"
            :filter-node-method="filterNode"
        >
          <template #default="{ node, data }">
            <span class="tree-node">
              <el-icon v-if="node.isLeaf"><Document/></el-icon>
              <el-icon v-else><Folder/></el-icon>
              <span>{{ node.label }}</span>
            </span>
          </template>
        </el-tree>
      </div>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-icon>
            <List/>
          </el-icon>
          <span>用户列表</span>
          <span v-if="currentOrgName" class="selection-hint">
            当前组织为: <el-tag type="success" effect="plain">{{ currentOrgName }}</el-tag>
          </span>
        </div>
      </template>

      <div class="query-form">
        <el-form :inline="true" :model="queryParams">
          <el-form-item label="用户名">
            <el-input
                v-model="search"
                placeholder="用户名"
                clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" :disabled="!currentDepartment">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table-toolbar">
        <el-button type="primary" @click="handleAdd" v-permission="['admin','insert_user']" :disabled="!currentDepartment">
          <el-icon>
            <Plus/>
          </el-icon>
          添加用户
        </el-button>
        <el-button
            type="danger"
            :disabled="!selecteds.length"
            @click="handleBatchDelete"
            v-permission="['admin']"
        >
          <el-icon>
            <Delete/>
          </el-icon>
          删除用户
        </el-button>
      </div>

      <!-- User Table -->
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          height="calc(100vh - 420px)"
          v-loading="loading"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="userId" label="ID" width="80"/>
        <el-table-column prop="userCode" label="用户名" width="120"/>
        <el-table-column prop="nickName" label="昵称"/>
        <el-table-column prop="orgCode" label="组织" width="120">
          <template #default="scope">
            <TableDictSelect
                :model-value="scope.row.orgCode"
                table-name="app_org"
                label-field="orgName"
                value-field="orgCode"
                display-only
            />
          </template>
        </el-table-column>
        <el-table-column prop="roleCode" label="角色 " width="120">
          <template #default="scope">
            <TableDictSelect
                :model-value="scope.row.roleCode"
                table-name="app_role"
                label-field="roleName"
                value-field="roleCode"
                display-only
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button v-permission="['admin','update_user']" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button v-permission="['admin']" size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="queryParams.current"
            v-model:page-size="queryParams.size"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleQuery"
            @current-change="fetchTableData"
        />
      </div>
    </el-card>
    <UserDialog ref="UserDialogRef" @submit="handleSubmit"/>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, watch} from 'vue'
import {
  Folder,
  Document,
  Search,
  Plus,
  Delete,
  List
} from '@element-plus/icons-vue'
import {tableInfoApi} from '@/api/core';
import { PageQuery, TreeNode} from "@/types/api";
import {OrgItem} from "@/views/org/org";
import {ElMessageBox, ElMessage} from 'element-plus'
import UserDialog from './edit.vue'
import {UserItem} from "@/views/user/user";
import TableDictSelect from '@/components/TableDictSelect.vue'

const UserDialogRef = ref<InstanceType<typeof UserDialog>>()
const treeRef = ref()
const treeFilterText = ref('')
const filteredTreeData = ref<TreeNode<OrgItem>[]>([])
//orgId
const currentDepartment = ref('')
const currentOrgName = ref('')
const currentOrgCode = ref('')

const search = ref('')

const queryParams = ref<PageQuery>({
  code: 'app_user',
  current: 1,
  size: 10,
  queryParams: [{
    paramName: "userCode",
    relation: "like",
    paramValue: ""
  }, {
    paramName: "orgCode",
    relation: "eq",
    paramValue: ""
  }],
  querySorts: [{
    paramName: "userId",
    order: "desc"
  }]
})

const tableData = ref<OrgItem[]>([])
const total = ref(0)
const loading = ref(false)
const selecteds = ref<OrgItem[]>([])

//属性映射
const treeProps = {
  children: 'children',
  label: 'label'
}

//触发树筛选
const filterTree = () => {
  treeRef.value?.filter(treeFilterText.value)
}

//树节点过滤逻辑
const filterNode = (value: string, data: TreeNode<OrgItem>) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}

//树点击
const handleNodeClick = (data: TreeNode<OrgItem>) => {
  currentDepartment.value = data.id
  currentOrgName.value = data.label
  currentOrgCode.value = data.data?.orgCode || ""
  handleQuery()
}

//搜索
const handleQuery = () => {
  queryParams.value.current = 1
  fetchTableData()
}

watch(search,(newVal)=> {
  if (queryParams.value.queryParams && queryParams.value.queryParams[0]) {
    queryParams.value.queryParams[0].paramValue = newVal
  }
})

watch(currentOrgCode, (newVal) => {
  if (queryParams.value.queryParams && queryParams.value.queryParams[1]) {
    queryParams.value.queryParams[1].paramValue = newVal
  }
})


//查询
const fetchTableData = () => {
  loading.value = true
  tableInfoApi.page(queryParams.value).then(res => {
    total.value = res.data.total
    tableData.value = res.data.records
  }).finally(() => {
    loading.value = false
  })
}

//重置
const resetQuery = () => {
  queryParams.value.size = 10
  search.value = ''
  handleQuery()
}

//多选
const handleSelectionChange = (val: OrgItem[]) => {
  selecteds.value = val
}

//新增
const handleAdd = () => {
  UserDialogRef.value?.openDialog(currentOrgCode.value)
}

//编辑
const handleEdit = (row: UserItem) => {
  UserDialogRef.value?.openDialog(currentOrgCode.value, row)
}

//保存数据
const handleSubmit = (data: UserItem) => {
  tableInfoApi.saveOrUpdate("app_user", data).then(() => {
    ElMessage.success("保存用户成功")
    queryOrgTree()
  })
}

//删除单条
const handleDelete = (row: UserItem) => {
  ElMessageBox.confirm(
      `是否确认删除用户 "${row.userCode}"？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    tableInfoApi.deleteById("app_user", "" + row.userId).then(() => {
      ElMessage.success("删除用户成功")
      queryOrgTree()
    })
  }).catch(() => {
    // 点击取消，不做操作
  })
}

//批量删除
const handleBatchDelete = () => {
  if (!selecteds.value.length) return

  ElMessageBox.confirm(
      `是否确认删除选中的 ${selecteds.value.length} 个用户？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    const ids = selecteds.value.map(item => item.orgId).join(',')
    tableInfoApi.deleteByIds("app_user", ids).then(() => {
      ElMessage.success("批量删除用户成功")
      selecteds.value = []
      queryOrgTree()
    })
  }).catch(() => {
    // 点击取消，不做操作
  })
}

//查询组织树
const queryOrgTree = () => {
  tableInfoApi.tree("app_org").then((res) => {
    filteredTreeData.value = res.data
    if (currentDepartment.value != null && currentDepartment.value != '') {
      handleQuery()
    }
  })
}

onMounted(() => {
  queryOrgTree()
})
</script>


<style scoped>
.container {
  display: flex;
  gap: 16px;
  height: 100%;
}

.tree-card {
  width: 300px;
  flex-shrink: 0;
}

.table-card {
  flex: 1;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.tree-search {
  margin-bottom: 16px;
}

.tree-container {
  height: calc(100vh - 300px);
  overflow-y: auto;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
}

.tree-actions {
  margin-left: auto;
  visibility: hidden;
}

:deep(.el-tree-node__content:hover) .tree-actions {
  visibility: visible;
}

.query-form {
  margin-bottom: 16px;
}

.table-toolbar {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.selection-hint {
  margin-left: 12px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

:deep(.el-table) {
  --el-table-border-color: #eaeaea;
}

:deep(.el-tree) {
  --el-tree-node-hover-bg-color: #f5f7fa;
}
</style>